<?php
require 'connection.php';
$GLOBALS['loginPageUrl'] = "http://projectx.x10.mx//login.php";
$GLOBALS['homePageUrl'] = "http://projectx.x10.mx/home.php";
$GLOBALS['logoutUrl'] = "http://projectx.x10.mx/accountValidator.php";
$GLOBALS['profilePage'] = "http://projectx.x10.mx/profile.php";
$GLOBALS['listingSalt'] = 678473527281691635271;
$GLOBALS['noPicImgUrl'] = "img/no-pic.jpeg";
function getResultArray($query, $pdo, $params=array()){
	$statement = $pdo->prepare($query);
	if(isset($params) && !empty($params)){
		foreach ($params as $key => $value) {
			$statement->bindValue($key, $value);
		}
	}
	$statement->execute();
	$array = $statement->fetchAll();
	return $array;
}

function registerExists($table, $fieldsAndValues, $pdo){
	$query = "SELECT * FROM $table WHERE ";
	$index = 0;
	foreach ($fieldsAndValues as $key => $value) {
		$query .= $table.".".str_replace(":", "", $key)."= $key";
		if(++$index < sizeof($fieldsAndValues)){
			$query .= " and ";
		}
	}
	$result = getResultArray($query,$pdo, $fieldsAndValues);
	return !empty($result);
}

//The keys in params must be preceded by semicolon -> :
function executeInsert($table, $params, $pdo){
	$index = 0;
	$columnNames = "";
	$values = "";
	foreach ($params as $key => $value) {
		$values .= $key;
		$columnNames .= str_replace(":", "", $key);
		if(++$index < sizeof($params)){
			$columnNames .= ",";
			$values .= ",";
		}
	}
	$query = "INSERT INTO $table ($columnNames) VALUES ($values)";
	$statement = $pdo->prepare($query);
	if($statement->execute($params)){
		return $pdo->lastInsertId();
	}else{
		return -1;
	}
}

function executeDelete($table, $paramsWhere, $pdo){
	$index = 0;
	$query = "DELETE FROM $table WHERE ";
	$whereString = "";
	foreach ($paramsWhere as $key => $value) {
		$whereString .= str_replace(":", "", $key)." = $key";
		if(++$index < sizeof($paramsWhere)){
			$whereString .= " and ";
		}
	}
	$query .= $whereString;
	$statement = $pdo->prepare($query);
	foreach ($paramsWhere as $key => $value) {
			$statement->bindValue($key, $value);
	}
	return $statement->execute();
}

function executeUpdate($table, $paramsSet, $paramsWhere, $pdo){
	$index = 0;
	$query = "UPDATE $table SET ";
	$setString = "";
	$whereString = "";
	foreach ($paramsSet as $key => $value) {
	 	$setString .= str_replace(":", "", $key)." = $key";
	 	if(++$index < sizeof($paramsSet)){
	 		$setString .= ",";
	 	}
	}

	foreach ($paramsWhere as $key => $value) {
		$whereString .= str_replace(":", "", $key)." = $key";
		if(++$index < sizeof($paramsWhere)){
			$whereString .= " and ";
		}
	}
	$query .= $setString;

	if(!empty($paramsWhere)){
		$query .= " WHERE ".$whereString;
	}
	$statement = $pdo->prepare($query);
	foreach ($paramsSet as $key => $value) {
			$statement->bindValue($key, $value);
	}
	foreach ($paramsWhere as $key => $value) {
			$statement->bindValue($key, $value);
	}
	return $statement->execute();
}

//Util File
// jS JsonString
function getJsonScriptFromResut($result){
	$pk = getHiddenListingPk($result['pk']);
	$title = strtoupper($result['title']);
	$imageUrl = $result['image_url'];
	$description = $result['description'];
	$price = ((float)$result['price']);
	$latitude = $result['latitude'];
	$longitude = $result['longitude'];
	$jS = "var result{$pk} = {
			  id: 'r{$pk}' ,
			  divId: \"{$pk}\",
			  mapLinkId: \"mapLink{$pk}\",
			  position: {
			    latitude: {$latitude}, 
			    longitude: {$longitude}
			  },
			  iconImage: {
			    path: \"img/marker.png\",
			    height:48,
			    width:42,
			    scaledHeight:48,
			    scaledWidth:42
			  },

			  markerString: '',

			  infoWindowString: '<div class=\"infoWindow2\" id=\"infoWindow_r{$pk}\">'+
							   ' <div class=\"imageContainer\" style=\"background-image: url(\'{$imageUrl}\');\">'+
							    '</div>'+
							    '<div class=\"infoWindowContents\">'+
							     ' <div class=\"i-w-headingContainer\">'+
							      '  <p class=\"i-w-headingTitle ellipsis\">{$title}</p><p class=\"i-w-price\">&#163;{$price}</p>'+
							     ' </div>'+
							     ' <div class=\"i-w-body\">'+
							      '  <p class=\"ellipsis\">{$description}</p>'+
							     ' </div>'+
							      '<div class=\"i-w-links\">'+
							        '<a class=\"moreInfoLink\" href=\"#\">MORE INFO</a><a class=\"closeLink\" href=\"#\" onclick=\"window.results.closeInfoBox()\">X</a>'+
							      '</div>'+
							   ' </div>'+
							   ' <div class=\"i-w-pin\">'+
							   '   <div>'+
							        ' </div>'+
							         '<div>'+
							         '</div>'+
							       '</div>'+
							     '</div>',
			  infoWindowData:{
			    pixelOffset:{
			      x:-30,
			      y: -80
			    },
			    width:210
			  }
			};";
	return $jS;
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

function goToUrl($url){
	//header("Location: ".$url);
	echo "<script>window.location = '$url'</script>";
}

function isNumber($n){
	return is_numeric($n);
}

function checkUserLoggedIn(){
	if(isset($_SESSION['loggedin']) and $_SESSION['loggedin'] == true){
		return true;
	}
	return false;
}

function isLoggedIn(){
	return isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && getLoggedInUser() != "";
}

function getLoggedInUser(){
	return $_SESSION['userLoggedIn'];
}

function createDirectory($dir){
	if(!file_exists($dir)){
		mkdir($dir, 0755, true);
	}
	return $dir;
}
function moveFiles($files,$dir){
	$uploads_dir = $dir;
	$paths = array();
	if(empty($files)){
		return $paths;
	}
	foreach ($files as $key => $value) {
	    if ($value['error'] == UPLOAD_ERR_OK) {
	        $tmp_name = $value["tmp_name"];
	        //print(explode(".", $value["name"])[1]);
	        //$name = $files["pictures"]["name"][$key];
	        $name = generateRandomString(7).".".explode(".", $value["name"])[1];
	        move_uploaded_file($tmp_name, "$uploads_dir/$name");
	        $paths[$key] = "$uploads_dir/$name";
	    }
	}
	return $paths;
}

function additionalInformationExists($userId){
	$query = "SELECT * FROM user_info WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$userId
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	return !empty($result);;
}

function getUserInformation($userId){
	$query = "SELECT user_info.*, user_gender.description AS 'gender'  FROM user_info INNER JOIN user_gender ON user_info.gender_fk = user_gender.pk WHERE user_fk = :user_fk";
	$params = array(
		":user_fk"=>$userId
		);
	$result = getResultArray($query, $GLOBALS['pdo'], $params);
	return $result[0];
}

function getPdo(){
	return $GLOBALS['pdo'];
}

function getAge($birthdate){
 return floor((time() - strtotime($birthdate))/31556926);
}

function formatDateString($dateString, $currrentFormatPattern, $newFormatPattern){
	$date = DateTime::createFromFormat($currrentFormatPattern, $dateString);
	$date = $date->format($newFormatPattern);
	return $date;
}

function checkLoggedIn(){
	if(!isLoggedIn()){
		goToUrl($GLOBALS['loginPageUrl']);
	}
}

function getListingCathegories(){
	$query = "SELECT pk, description FROM result_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingBedTypes(){
	$query = "SELECT pk, description FROM result_bed_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingCancellationTypes(){
	$query = "SELECT pk, description FROM result_cancellation_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getListingRoomTypes(){
	$query = "SELECT pk, description FROM result_room_type";
	return getResultArray($query, $GLOBALS['pdo']);
}

function getGenders(){
	$query = "SELECT pk, description FROM user_gender";
	return getResultArray($query, $GLOBALS['pdo']);
}

function generateListedResultsArray($results){
	unset($_SESSION['listedResults']);
	$_SESSION['listedResults'] = array();
	foreach ($results as $r) {
	      $pk = $r['pk'];
	      $key = generateRandomString(10);
	      $_SESSION['listedResults'][$key] = $pk;
	}
}

function getHiddenListingPk($pk){
	return array_search($pk, $_SESSION['listedResults']); 
}

function emptyString($str){
	return !isset($str) || trim($str) == "";
}

function logout(){
	unset($_SESSION['loggedin']);
	session_destroy();
}

function getJSON($json){
	return json_encode($json);
}

function getURLFromReferer($url=""){
	$referer = $_SERVER['HTTP_REFERER'];
	$refererArray = explode("/", $referer);
	$refererArray[sizeof($refererArray)-1] = $url;
	$referer = implode("/", $refererArray);
	return $referer;
}

function doLogIn($userPk){
	$_SESSION['loggedin'] = true;
	$_SESSION['userLoggedIn'] = $userPk;
}

function ifsetor(&$variable, $default = null) {
    if (isset($variable)) {
        $tmp = $variable;
    } else {
        $tmp = $default;
    }
    return $tmp;
}

function displayTextIfExists($var, $tag){
	if(isset($var) && !emptyString($var)){
		return "<p>{$tag}: {$var}</p>";
	}
}

function displayImage($url){
	if(isset($url) && !emptyString($url)){
		return "<img src='{$url}' />";
	}
}

function printSelected($field, $value){
	return ($field != "" && $field == $value ? "selected":"");
}

?>